import React, {useState, useEffect, useRef} from "react";
import {Table, Button, Modal, Switch} from "antd";
import {EditOutlined, DeleteOutlined, ExclamationCircleOutlined} from '@ant-design/icons'
import axios from "axios";
import UserForm from "../../../components/UserManage/UserForm";

export default function UserManege() {
    const [dataSource, setDataSource] = useState([])
    const [isAddVisible, setIsAddVisible] = useState(false)
    const [isUpdateVisible, setIsUpdateVisible] = useState(false)
    const [isUpdateDisabled, setIsUpdateDisabled] = useState(false)
    const [roleList, setRoleList] = useState([])
    const [regionList, setRegionList] = useState([])
    const [current, setCurrent] = useState(null)

    const addForm = useRef(null)
    const updateForm = useRef(null)
    const {roleId,region,username} = JSON.parse(localStorage.getItem("token"))
    const roleObj = {
        "1": "superAdmin",
        "2": "admin",
        "3": "editor"
    }
    useEffect(()=>{
        axios.get("/users?_expand=role").then(res=>{
            const list = res.data
            // 用户列表功能当前用户只能查看和编辑比自己级别小的用户，这应该在后端根据用户返回相对应的用户列表，这里手动过滤实现
            // setDataSource(list)
            setDataSource(roleObj[roleId]==="superAdmin"?list:[
                ...list.filter(item=>item.username===username),
                ...list.filter(item=>item.region===region && roleObj[item.roleId]==="editor")
            ])
        })
    },[])
    useEffect(() => {
        axios.get("/regions").then(res => {
            const list = res.data
            setRegionList(list)
        })
    }, [])
    useEffect(() => {
        axios.get("/roles").then(res => {
            const list = res.data
            setRoleList(list)
        })
    }, [])

    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters: [
                ...regionList.map(item=>({
                    text:item.title,
                    value:item.value
                })),
                {
                    text:"全球",
                    value:"全球"
                }

            ],
            onFilter:(value,item)=>{
                if(value==="全球"){
                    return item.region===""
                }
                return item.region===value
            },
            render:(region)=>{
                return <b>{region?region:'全球'}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render:(role)=>{
                return role?.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'username',
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render:(roleState, item) =>{
                return <Switch checked={roleState} disabled={item.default}
                               onChange={()=>handleChange(item)}> </Switch>
            }
        },
        {
            title: '操作',
            render:(item)=>{
                return <div>
                    <Button type="primary" shape="circle" icon={<EditOutlined />}
                            disabled={item.default} onClick={()=>handleUpdate(item)}/>
                    <Button type="danger" shape="circle" icon={<DeleteOutlined />}
                            onClick={()=>confirmMethod(item)} disabled={item.default}/>
                </div>
            }
        }
    ];

    const { confirm } = Modal;
    const confirmMethod = (item)=>{
        confirm({
            title: '你确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            // content: 'Some descriptions',
            onOk() {
                deleteMethod(item)
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    const deleteMethod = (item)=>{
        console.log(item)
        // 当前页面同步状态 + 后端同步
        axios.delete("/users/" + item.id).then(res=>{
            setDataSource(dataSource.filter(data=>data.id!==item.id))
        })

    }
    const addFormOK = ()=>{
        addForm.current.validateFields()
            .then(values => {
                setIsAddVisible(false)
                addForm.current.resetFields();
                axios.post("/users",{
                    ...values,
                    "roleState": true,
                    "default": false,
                }).then(res =>{
                    console.log(res.data)
                    // setDataSource([...dataSource,res.data])
                    setDataSource([...dataSource,{
                        ...res.data,
                        role:roleList.filter(item=>item.id===values.roleId)[0]
                    }])
                })

                // onCreate(values);
            })
            .catch(info => {
                console.log('Validate Failed:', info);
            });
    }
    const handleChange = (item)=>{
        // console.log(item)
        item.roleState = !item.roleState

        axios.patch("/users/" + item.id,{
            roleState:item.roleState
        }).then(res=>{
            setDataSource([...dataSource])
        })
    }
    const handleUpdate = (item)=>{
        setIsUpdateVisible(true)
        setTimeout(()=>{
            if(item.roleId===1){
                //禁用
                setIsUpdateDisabled(true)
            }else{
                //取消禁用
                setIsUpdateDisabled(false)
            }
            updateForm.current.setFieldsValue(item)
        },0)
        setCurrent(item)
    }
    const updateFormOK = ()=>{
        updateForm.current.validateFields().then(value => {
            // console.log(value)
            setIsUpdateVisible(false)

            axios.patch("/users/" + current.id,value)
                .then(res=>{
                    setDataSource(dataSource.map(item=>{
                        if(item.id===current.id){
                            return {
                                ...item,
                                ...value,
                                role:roleList.filter(data=>data.id===value.roleId)[0]
                            }
                        }
                        return item
                    }))
                    setIsUpdateDisabled(!isUpdateDisabled)
                })
        })
    }

    return (
        <div>
            <Button type="primary" onClick={()=>setIsAddVisible(true)}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} rowKey={(item=>item.id)}
                   pagination={{
                       pageSize: 5
                   }}/>;
            <Modal
                visible={isAddVisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={()=>setIsAddVisible(false)}
                onOk={() => addFormOK()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}/>
            </Modal>
            <Modal
                visible={isUpdateVisible}
                title="更新用户"
                okText="更新"
                cancelText="取消"
                onCancel={() => {
                    setIsUpdateVisible(false)
                    setIsUpdateDisabled(!isUpdateDisabled)
                }}
                onOk={() => updateFormOK()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={updateForm}
                          isUpdateDisabled={isUpdateDisabled} isUpdate={true}/>
            </Modal>
        </div>
    )
}